package jsf.uss.beans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;

import jsf.uss.controllers.ClientController;
import jsf.uss.factory.HibernateUtil;
import jsf.uss.models.Client;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.event.RowEditEvent;

@ManagedBean(name = "clientBean")
@ViewScoped
public class ClientBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 3633987691607558117L;

    @Inject
    public ClientController clientRepository;
    public Client client = new Client();

    public ClientBean() {
    }

    public Client getClient() {
	return client;
    }

    public void setClient(Client client) {
	this.client = client;
    }

    public List<Client> getAllClients() {
	return clientRepository.getAll();
    }

    public List<Long> getClientIds() {
	Session session = HibernateUtil.getSessionFactory().openSession();
	Transaction transaction = session.beginTransaction();

	Query query = session.getNamedQuery("Client.findAllIds");
	List<Long> result = castList(Long.class, query.list());

	transaction.commit();
	session.flush();
	session.close();

	return result;
    }

    public Client getClientById(Long id) {
	this.client = clientRepository.getById(id);

	return client;
    }

    public void create() {
	this.client = new Client();
    }

    public void add(ActionEvent actionEvent) {
	clientRepository.add(this.client);

	FacesContext.getCurrentInstance()
		.addMessage(
			null,
			new FacesMessage("Added new client - "
				+ this.client.getName()));
    }

    public void update() {
	clientRepository.update(this.client);
    }

    public void cancel(RowEditEvent event) {
	FacesMessage msg = new FacesMessage("Client Edit Cancelled",
		((Client) event.getObject()).getName());

	FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    // public String delete() {
    // clientRepository.remove(id);
    //
    // return "ClientsList.xhtml?faces-redirect=true";
    // }

    public void delete(ActionEvent actionEvent) {
	clientRepository.remove(this.client);

	// return "ClientsList.xhtml?faces-redirect=true";
    }

    public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
	List<T> r = new ArrayList<T>(c.size());
	for (Object o : c)
	    r.add(clazz.cast(o));
	return r;
    }
}
